﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IRepository;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebServe_demo.Utility;
using WebServe_demo.Utility._MD5;

namespace WebServe_demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class WriterInfoController : ControllerBase
    {
        private readonly IWriterInfoRepository _iWriterInfoRepository;
        public  WriterInfoController(IWriterInfoRepository iWriterInfoRepository)
        {
            this._iWriterInfoRepository = iWriterInfoRepository;
        }
        [HttpGet("Writer")]
        public async Task<ApiResult> Writer()
        {
            var writer = await _iWriterInfoRepository.QueryAsync();
            return ApiResultHelper.Success(writer);
        }
        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name ,string username,string userpwd)
        {
            #region 数据验证
            WriterInfo writer = new WriterInfo
            {
                Name = name,
                //加密密码

                Username = username,
                UserPwd = MD5Helper.MD5Encrypt32(userpwd)
            };

            #endregion
            //判断数据库中是否存在账号和现添加的账号密码相同
          var oldWriter = await _iWriterInfoRepository.FindAsync(c => c.Username == username);
            if (oldWriter != null) return ApiResultHelper.Error("账号已经存在");

            bool b = await _iWriterInfoRepository.CreateAsync(writer);
            if (!b) return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(writer);
             

        }
        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(string name)
        {
            int id = Convert.ToInt32(this.User.FindFirst("Id").Value);
            var writer = await _iWriterInfoRepository.FindAsync(id);
            writer.Name = name;
            bool b = await _iWriterInfoRepository.EditAsync(writer);
            if (!b) return ApiResultHelper.Error("修改失败");

            return ApiResultHelper.Success(b);
        }
        [HttpDelete("Delete")]
        public async Task<ApiResult> Delete(int id)
        {
            bool b = await _iWriterInfoRepository.DeleteAsync(id);
            if (!b) return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(b);


        }
        [AllowAnonymous]
        [HttpGet("Find")]
        public async Task<ApiResult> FindByid([FromServices]IMapper iMapper,int id )
        {
            WriterInfo writer = await _iWriterInfoRepository.FindAsync(id);
            //创建一个映射，目的是为了不返回密码
            var writerDTO =  iMapper.Map<WriterDTO>(writer);
            return ApiResultHelper.Success(writerDTO);
        }


    }
}
